/**
 * @file 发布文章页面
 * @author wangshaozhi(wangshaozhi@baidu.com)
 */

import {useCallback, useEffect, useMemo, useRef} from "react";
import {observer} from "mobx-react";
import {Button, Table, Tag, message} from 'antd';
import {useTitle} from "react-use";
import {useHistory} from "react-router-dom";
import request from '../../../../request';

// store
import {MainStore} from "../../../../store/mainStore";

// constants
import {ARTICLE_LIST_URL, PUBLISH_ARTICLE_URL} from "../../../../request/url";

// style
import cls from './index.module.scss';
import Article from "../../../../model/article";

interface IProps {
    store: MainStore;
}

export const PublishArticle: React.FC<IProps> = observer(({
    store
}) => {
    const getArticleListRef = useRef<boolean>(true);
    const history = useHistory();
    const {
        articleStore,
        sideBarStore
    } = store;
    useTitle('发布文章');

    const getArticleList = useCallback(async () => {
        try {
            const author = JSON.parse(localStorage.getItem('user') || 
            '{}').username;
            const res = await request({
                method: 'post',
                url: ARTICLE_LIST_URL,
                data: {
                    author
                }
            });
            articleStore.update({
                articleList: res.data
            })
        }
        catch (e) {

        }
    }, [articleStore]);

    useEffect(() => {
        if (getArticleListRef.current) {
            getArticleList();
            getArticleListRef.current = false;
        }
    }, [articleStore, getArticleList, store]);

    const onPublishHandler = useCallback(async(article: Article) => {
        if (article.isPublish === Article.EPublish.PUBLISHED) {
            message.warning('该篇文章已发布，请选择未发布文章~');
            return;
        }
        try {
            const res = await request({
                method: 'post',
                url: PUBLISH_ARTICLE_URL,
                data: {
                    id: article.id
                }
            });
            const {
                code,
                msg
            } = res.data;
            if (code === 0) {
                message.success(msg);
                history.push('/');
                sideBarStore.update({
                    currSelectedKeys: ['index']
                });
                return;
            }
            message.error(msg);
        }
        catch (e) {

        }
    }, [history, sideBarStore]);

    const columns = useMemo(() => ([
        {
            dataIndex: 'id',
            title: 'id'
        },
        {
            dataIndex: 'title',
            title: '标题'
        },
        {
            dataIndex: 'introduction',
            title: '简介'
        },
        {
            dataIndex: 'publishTime',
            title: '发布时间'
        },
        {
            dataIndex: 'typeName',
            title: '类型'
        },
        {
            dataIndex: 'viewsCount',
            title: '阅读数量'
        },
        {
            title: '发布状态',
            dataIndex: 'isPublish',
            render: (isPublished: string) => (
                (+isPublished as Article.EPublish) === Article.EPublish.NOT_PUBLISH
                ? <Tag color="red">未发布</Tag>
                : <Tag color="#87d068">已发布</Tag>
            )
        },
        {
            dataIndex: 'action',
            title: '操作',
            render: (_: any, record: any) => (
                <Button
                    size="small"
                    type="primary"
                    className={cls.editBtn}
                    onClick={() => onPublishHandler(record)}
                >
                    发布文章
                </Button>
            )
        }
    ]), [onPublishHandler]);

    return (
        <div className={cls.wrapper}>
            <Table
                columns={columns}
                rowKey={item => item.id}
                dataSource={articleStore.articleList}
                pagination={{
                    pageSize: 7
                }}
            />
        </div>
    );
});